from django.core.paginator import Paginator
from django.http import HttpResponse
from django.views.decorators.http import require_POST, require_GET, require_http_methods

from utils import response_code
from utils.customer_util import CustomerUtil
from utils.response_code import ResponseCode
from .models import Dept

# Create your views here.
"""
在函数上通过添加装饰器  约束函数能处理的请求方式
@require_POST   只处理post请求
@require_GET   只处理get请求
@require_http_methods(['GET','POST'])   只处理指定的请求方式

401  没有认证
403  没有权限
404  url错误
405  请求方式错误
"""


@require_POST
def dept_page(request):
    """部门分页"""
    params = CustomerUtil.get_request_params(request)
    page = params.get('page', 1)
    size = params.get('size', 5)

    dept_list = Dept.objects.all().order_by('-id')
    paginator = Paginator(dept_list, size)
    total = paginator.count
    current_page = paginator.page(page)
    table_data = list(current_page.object_list.values())

    response = {
        'total': total,
        'table_data': table_data,
        "code": ResponseCode.BUSINESS_SUCCESS,
        "message": "success"
    }

    return CustomerUtil.response_json(response)


@require_GET
def dept_list(request):
    dept_list = list(Dept.objects.all().values('id', 'name'))
    return CustomerUtil.response_json({
        'depts': dept_list,
        "code": ResponseCode.BUSINESS_SUCCESS
    })


@require_POST
def dept_insert_edit(request):
    """部门添加/编辑"""
    form = CustomerUtil.get_request_params(request)
    try:
        if form.get('id'):
            # 编辑
            Dept.objects.filter(id=form.get('id')).update(**form)
        else:
            # 新增
            Dept(**form).save()
        response = {
            'code': ResponseCode.BUSINESS_SUCCESS,
            'message': '操作成功'
        }
    except Exception as e:
        response = {
            'code': ResponseCode.BUSINESS_ERROR,
            'message': str(e)
        }
    return CustomerUtil.response_json(response)


@require_GET
def dept_one(request, id):
    """根据id获取部门详情"""
    dept = Dept.objects.filter(id=id).values().first()
    return CustomerUtil.response_json({
        'code': ResponseCode.BUSINESS_SUCCESS,
        'message': 'success',
        'dept': dept
    })


@require_GET
def dept_delete(request, id):
    """删除部门信息"""
    try:
        Dept.objects.filter(id=id).delete()
        response = {
            "code": ResponseCode.BUSINESS_SUCCESS,
            "message": "删除成功"
        }
    except Exception as e:
        response = {
            'code': ResponseCode.BUSINESS_ERROR,
            'message': "部门被占用"
        }
    return CustomerUtil.response_json(response)
